<template>
  <div v-loading="detailInfoShow">
    <div class="requestAdd">
      <!-- 筛选按钮 -->

      <div class="search-button" v-if="!contactAddShow">
        <el-button
        v-if="activeName == 'approval' && flowInfoList.length"
        @click="handleEvaluate()"
        class="btn save"
        ><el-icon class="icon" color="#fff"> <Comment /> </el-icon
        >评论</el-button
      >
        <el-button v-if="activeName == 'approval' && flowInfoList.length" @click="handlePrint()" v-print="prints" class="btn add"
        ><el-icon class="icon" color="#fff"> <Printer /> </el-icon
        >打印</el-button
      >
        <el-button class="btn direction" @click="handleBack"
          ><el-icon class="icon" color="#fff"> <Back /> </el-icon
          >返回</el-button
        >
      </div>

      <el-tabs type="border-card" v-model="activeName">
        <el-tab-pane label="申请信息" name="info">
          <el-collapse v-model="activeNames">
            <el-form
              :model="requestForm"
              ref="requestFormRef"
              :rules="queryRules"
              label-width="120px"
              v-enterToNext
              :disabled="pageType === 'detail' || pageType === 'check'"
            >
              <!-- 基础信息 -->
              <el-collapse-item
                name="1"
                v-if="!contactAddShow"
                class="transform-down"
              >
                <template #title>
                  <span class="circle"></span>
                  <span class="collapse-title"
                    >{{
                      pageType !== "detail" && pageType !== "check "
                        ? pageType === "add"
                          ? "新增"
                          : "编辑"
                        : ""
                    }}知识产权申请信息</span
                  >
                </template>
                <div class="request-info">
                  <el-row>
                    <el-col :span="6">
                      <el-form-item label="申请编号：">
                        <el-input
                          disabled
                          v-model="requestForm.intellectualPropertyCode"
                          placeholder="自动获取"
                          clearable
                          class="search-input"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="申请日期：" prop="applicationTime">
                        <el-date-picker
                          v-model="requestForm.applicationTime"
                          format="YYYY/MM/DD HH:mm:ss"
                          style="width: 100%"
                          class="search-input"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          type="datetime"
                          placeholder="请选择"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item
                        label="经办人："
                        prop="userId"
                      >
                        <el-select
                          v-model="requestForm.userId"
                          placeholder="请选择"
                          clearable
                          filterable
                          class="search-input"
                          @change="handleUserChange"
                          value-key="userId"
                          placement="bottom-end"
                        >
                          <el-option disabled :value="null">
                            <div class="auto-top">
                              <span class="auto-item">人员姓名</span>
                              <span class="auto-item">联系方式</span>
                              <span class="auto-item">职位</span>
                              <span class="auto-item">部门</span>
                            </div>
                          </el-option>
                          <el-option
                            v-for="dict in userList"
                            :key="dict.userId"
                            :value="dict.userId"
                            :label="dict.nickName"
                          >
                            <div style="display: flex">
                              <div class="auto-item" :title="dict.nickName">
                                {{ dict.nickName }}
                              </div>
                              <div class="auto-item" :title="dict.phonenumber">
                                {{ dict.phonenumber ? dict.phonenumber : "--" }}
                              </div>
                              <div class="auto-item" :title="dict.postName">
                                {{ dict.postName ? dict.postName : "--" }}
                              </div>
                              <div class="auto-item" :title="dict.fullDeptName">
                                {{
                                  dict.fullDeptName ? dict.fullDeptName : "--"
                                }}
                              </div>
                            </div>
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="经办部门：">
                        <el-input
                          disabled
                          v-model="requestForm.deptName"
                          placeholder="自动获取"
                          clearable
                          class="search-input"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="申请类型：" prop="applicationTypes">
                        <el-select
                          v-model="requestForm.applicationTypes"
                          placeholder="请选择"
                          clearable
                          multiple
                          style="width: 100%; height: 100%"
                        >
                          <el-option
                            v-for="dict in applicationList"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item
                        label="预申请名称："
                        prop="preApplicationName"
                      >
                        <el-input
                          v-model="requestForm.preApplicationName"
                          placeholder="请输入"
                          clearable
                          class="search-input"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                  <el-form-item label="申请单位：" prop="applicantUnit">
                    <el-input
                      v-model="requestForm.applicantUnit"
                      placeholder="请输入"
                      clearable
                      maxlength="20"
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="24">
                      <el-form-item label="内容描述：" prop="details">
                        <el-input
                          style="width: 100%"
                          v-model="requestForm.details"
                          type="textarea"
                          maxlength="2000"
                          placeholder="请输入"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="24">
                      <el-form-item label="备注：">
                        <el-input
                        maxlength="2000"
                          style="width: 100%"
                          v-model="requestForm.remark"
                          type="textarea"
                          placeholder="请输入"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="6">
                      <el-form-item label="附件：" prop="suppFileInfoVos">
                        <Upload
                          :fileList="requestForm.suppFileInfoVos"
                          :isFull="true"
                          :limit="10"
                          :showButton="true"
                          @success="(result) => uploadSuccess(result)"
                          @deleteFile="(result) => uploadRemove(result)"
                          :isCanDelete="
                            pageType == 'detail' || pageType == 'check'
                              ? false
                              : true
                          "
                          :disabled="
                            pageType == 'detail' || pageType == 'check'
                          "
                        />
                        <!-- accept=".jpg,.png" -->
                      </el-form-item>
                    </el-col>
                  </el-row>
                </div>
              </el-collapse-item>
            </el-form>
          </el-collapse>
        </el-tab-pane>
        <el-tab-pane label="审批进度" name="approval">
          <template v-if="auditList.length">
            <div class="contact-info" id="print-iframe" >
          <!-- 步骤栏 -->
           <div :class="!printFlag? 'steps-box' : 'steps-print-box '">
              <el-steps
                :class="flowInfoList.length > 7 ? 'BigSteps' : 'SmallSteps'"
                :active="flowingStep"
                finish-status="success"
              >
                <el-step v-for="(item, index) in flowInfoList" :key="index">
                  <template #title>
                    <span :title="item.name">
                      {{ item.name }}
                    </span>
                  </template>
                  <template #description>
                    <div>
                      <p class="ription">{{ item.auditDate }}</p>
                      <p class="ription">{{ item.auditEmp }}</p>
                    </div>
                  </template>
                </el-step>
              </el-steps>
            </div>
            <!-- 表格数据 -->
            <el-table
              :data="auditList"
              border
              :height="'100%'"
              :header-cell-style="{ 'text-align': 'center' }"
              sum-text=""
            >
              <!-- 操作模式 -->
              <el-table-column label="流程节点" prop="name" min-width="120">
              </el-table-column>
              <el-table-column
                label="审核人"
                prop="createUserName"
                min-width="120"
              >
              </el-table-column>
              <el-table-column
                label="审核时间"
                prop="createTime"
                min-width="120"
              >
              </el-table-column>
              <el-table-column
                label="审核意见"
                prop="resultName"
                min-width="120"
              >
              </el-table-column>
              <el-table-column label="审核备注" prop="remark" min-width="120">
              </el-table-column>
            </el-table>
          </div>
            <!-- 评论 -->
            <el-table
            style="margin-top: 60px"
            :data="evaluateList"
            border
            :height="'100%'"
            :header-cell-style="{ 'text-align': 'center' }"
            sum-text=""
          >
            <!-- 操作模式 -->
            <el-table-column label="评论内容" prop="content" min-width="500">
            </el-table-column>
            <el-table-column
              label="评论人"
              prop="createUserName"
              min-width="120"
            >
            </el-table-column>
            <el-table-column label="评论时间" prop="createTime" min-width="120">
            </el-table-column>
          </el-table>
          </template>
          <div v-else>暂无审核</div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <el-dialog
      :title="''"
      v-model="evaluateDialogShow"
      width="600px"
      append-to-body
    >
      <el-form-item label="评论内容：" label-width="90">
        <el-input
          style="width: 100%"
          v-model="evaluateInfo"
          placeholder=""
          type="textarea"
          rows="5"
          maxlength="500"
          clearable
        />
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            style="color: #fff; background-color: rgba(67, 207, 124, 1)"
            @click="saveEvaluate()"
            >保存</el-button
          >

          <el-button style="background-color: #fff" @click="closeEvaluate()"
            >取 消</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import Upload from "@/components/Upload/index";
import { addEvaluateApi, getEvaluateListApi } from "@/api/pub.js";
import { getUserListApi } from "@/api/information/customer";
import { getPropertyDetailApi, selectAuditList } from "@/api/serve/property";
import { getDictsApi } from "@/api/dict";
import { ElMessage, ElMessageBox } from "element-plus";
const emit = defineEmits([
  // 客户新增组件显隐
  "requestDtlShow",
  // 更新客户新增组件显隐
  "update:requestDtlShow",
  // 刷新父组件表格数据
  "refreshList",
]);
const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "detail",
  },
  // 合同用印id
  contractId: {
    type: Number,
    default: null,
  },
  // 合同用印编号
  contractCode: {
    type: Number,
    default: null,
  },
});
const activeName = ref('info')
// 折叠栏默认展开
const activeNames = ref(["1", "2", "3"]);
// 客户表单引用
const requestFormRef = ref();
// 新增联系人表单显隐
const contactAddShow = ref(false);

// 详情加载效果
const detailInfoShow = ref(false);

// 申请类型列表
const applicationList = ref([]);
//审核进度列表数据
let auditList = ref([]);

//审核进度条数据
const flowInfoList = ref([]);
//当前进度
const flowingStep = ref(0);

// 评论
const evaluateDialogShow = ref(false);
// 评论内容
const evaluateInfo = ref("");
// 评论列表
const evaluateList = ref([]);

// 客户表单数据模板
const requestFormTemplate = {
  intellectualPropertyCode: "", //申请编号
  userId: null, // 经办人id
  applicationTime: "", // 申请日期
  details: "", // 	内容描述
  applicationTypes: [], // 申请类型
  preApplicationName: "", // 	预申请名称
  applicantUnit:"", // 申请单位
  deptName: "", // 申请部门
  remark: "", //备注
  suppFileInfoVos: [], // 知识产权附件
  type: 0, // 	按钮类型0：存为草稿；1；提交
};

const data = reactive({
  // 客户表单
  requestForm: JSON.parse(JSON.stringify(requestFormTemplate)),
  // 客户表单校验规则
  queryRules: {
    applicationTime: [
      { required: true, message: "请选择申请日期", trigger: "change" },
    ],
    userId: [{ required: true, message: "请选择经办人", trigger: "change" }],
    applicationTypes: [
      { required: true, message: "请选择申请类型", trigger: "change" },
    ],
    details: [{ required: true, message: "请输入内容描述", trigger: "blur" }],
    preApplicationName: [
      { required: true, message: "请输入预申请名称", trigger: "blur" },
    ],

    suppFileInfoVos: [
      { required: true, message: "请上传附件", trigger: "change" },
    ],
  },
  // 用户列表
  userList: [],
});

const { requestForm, queryRules, userList } = toRefs(data);

import print from "vue3-print-nb";

// 使用自定义指令
const vPrint = print;
const printFlag = ref(false);

let prints = {
  id: "print-iframe",
  popTitle: "配置页眉标题", // 打印配置页上方的标题
  extraHead: "", // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
  preview: false, // 是否启动预览模式，默认是false
  previewTitle: "预览的标题", // 打印预览的标题
  previewPrintBtnLabel: "预览结束，开始打印", // 打印预览的标题下方的按钮文本，点击可进入打印
  zIndex: 20002, // 预览窗口的z-index，默认是20002，最好比默认值更高
  previewBeforeOpenCallback() {
    console.log("正在加载预览窗口！");
  }, // 预览窗口打开之前的callback
  previewOpenCallback() {
    console.log("已经加载完预览窗口，预览打开了！");
  }, // 预览窗口打开时的callback
  // 开始打印之前的callback
  beforeOpenCallback() {
    
    console.log("开始打印之前！");
   
  },
  openCallback() {
    console.log("执行打印了！");
  }, // 调用打印时的callback
  closeCallback() {
    console.log("关闭了打印工具！");
    printFlag.value= false
  }, // 关闭打印的callback(无法区分确认or取消)
  clickMounted() {
    console.log("点击v-print绑定的按钮了！");
    
  },
  standard: "",
  extarCss: "",
};

const handlePrint = ()=>{
  printFlag.value = true
}

// 处理评论按钮点击
const handleEvaluate = () => {
  evaluateDialogShow.value = true;
};

// 保存评论
const saveEvaluate = async () => {
  if (!evaluateInfo.value) return ElMessage.info("请输入评论内容！");
  const data = {
    businessId: requestForm.value.intellectualPropertyId,
    content: evaluateInfo.value,
    modelType: 6,
  };
  const result = await addEvaluateApi(data);
  if (result.code === 200) {
    ElMessage.success(result.msg);
    evaluateDialogShow.value = false;
    evaluateInfo.value = "";
    getEvaluateList()
  }
};

// 关闭评论弹窗
const closeEvaluate = () => {
  evaluateDialogShow.value = false;
  evaluateInfo.value = "";
};

// 获取评价列表
const getEvaluateList = async () => {
  const data = {
    businessId: requestForm.value.intellectualPropertyId,
    modelType: 6,
  };
  const result = await getEvaluateListApi(data);
  evaluateList.value = result.data || []
};

/**
 * @description: 返回
 */
const handleBack = () => {
  if (props.pageType === "detail" || props.pageType === "check") {
    emit("updateFollowAddShow", false);
    emit("update:requestDtlShow", false);
    requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
  } else {
    ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
    })
      .then(async () => {
        emit("update:requestDtlShow", false);
        requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
      })
      .catch(() => {});
  }
};

/**
 * @description: 处理人员选择
 * @param {Number} value 选择值
 */
const handleUserChange = (value) => {
  if (value) {
    const selectUser = userList.value.find((item) => item.userId === value);
    if (selectUser) {
      requestForm.value.deptName = selectUser.dept.deptName;
    }
  } else {
    requestForm.value.deptName = "";
  }
};

/**
 * @description: 文件上传成功处理
 * @param {Object} response 文件信息
 */
function uploadSuccess(response) {
  requestForm.value.suppFileInfoVos.push({ ...response, businessType: 28 });
}

/**
 * @description: 删除文件
 * @param {Number} index 当前文件索引
 */
function uploadRemove(index) {
  requestForm.value.suppFileInfoVos.splice(index, 1);
}

/**
 * @description: 处理详情信息
 * @param {Number} id
 */
const handleDetailInfo = async (id) => {
  try {
    detailInfoShow.value = true;
    const res = await getPropertyDetailApi(id);
    if (res.code == 200) {
      requestForm.value.intellectualPropertyId = id
      requestForm.value = {
        ...res.data,
      };
      getEvaluateList()
      // 存在为null无法push场景
      if (!requestForm.value.suppFileInfoVos) {
        requestForm.value.suppFileInfoVos = [];
      }

      const resAudit = await selectAuditList(id);
      auditList.value = resAudit.data;
      if (resAudit.data.length) {
        flowInfoList.value = resAudit.data[0].chartVo.flowList;
        flowingStep.value = resAudit.data[0].chartVo.flowingStep;
      }
    }
    detailInfoShow.value = false;
  } catch (error) {
    detailInfoShow.value = false;
  }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  // 申请类型0：软件著作权；1：发明专利；2：实用新型专利；3：论文
  await getDictsApi("erp_application_type").then((res) => {
    if (res.code === 200) {
      applicationList.value = res.data;
    }
  });
  await getUserListApi({}).then((res) => {
    if (res.length > 0) {
      userList.value = res;
    }
  });
}

onMounted(() => {
  getDicts();
});

defineExpose({
  handleDetailInfo,
});
</script>
<style lang="scss" scoped>
.requestAdd {
  padding: 20px 20px;
  width: 100%;
  height: 100%;

  .request-info {
    padding: 20px 20px 5px 20px;
    background-color: #f0f0f0;
    margin: 10px 0;
  }

  .contact-info {
    padding-top: 20px;
  }

  :deep(.el-table) {
    th.el-table__cell {
      background: #f8f8f8 !important;
    }
  }

  :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
    width: 268px !important;
    height: 34px !important;
  }

  .search-input {
    width: 268px;
    height: 34px;
  }

  .image-content {
    width: 100%;
    line-height: 0px;
    overflow: auto;
  }
  .ription {
    color: #8f8f8f;
    line-height: 16px;
    font-size: 12px;
  }
  :deep(.el-step__head.is-success) {
    color: #3399ff;
    border-color: #3399ff;
    position: relative;
  }
  :deep(.el-step__title) {
    font-size: 16px;
    line-height: 38px;
    position: absolute;
    top: -38px;
    width: 140px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  :deep(.el-step__title.is-success) {
    color: #3399ff;
  }
}

.auto-top {
  width: 100%;
  position: absolute;
  top: 0px;
  display: flex;
  font-weight: bold;
  background-color: #fff;
}

.auto-item {
  width: 125px;
  text-align: left;
  white-space: nowrap;
  /* 禁止换行 */
  overflow: hidden;
  /* 隐藏超出部分 */
  text-overflow: ellipsis;
  /* 使用省略号表示超出部分 */
}

.el-autocomplete .el-autocomplete-suggestion {
  max-height: 200px;
  /* 设置最大高度 */
  overflow-y: auto;
  /* 超出高度时显示滚动条 */
}
.el-table {
  border: var(--el-table-border);
}
</style>
